//
//  YNUser.m
//  Messenger
//
//  Created by OC on 15/1/15.
//  Copyright (c) 2015年 李健. All rights reserved.
//
//  用户实体类
//

#import "YNUser.h"
#import "YNOrgTree.h"
#import "XMPPDataSecurity.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"

@implementation YNUser
+ (NSString *)userNo
{
    return @"userNo";
}

+ (NSString *)userId
{
    return @"userId";
}

+ (NSString *)userName
{
    return @"userName";
}

+ (NSString *)gender
{
    return @"gender";
}

+ (NSString *)dayOfBirth
{
    return @"dayOfBirth";
}

+ (NSString *)telephone
{
    return @"telephone";
}

+ (NSString *)email
{
    return @"email";
}

+ (NSString *)post
{
    return @"post";
}

+ (NSString *)ownPart
{
    return @"ownPart";
}

+ (NSString *)headUrl
{
    return @"headUrl";
}

+ (NSString *)sigature
{
    return @"sigature";
}

+ (NSString *)userType
{
    return @"userType";
}

+ (NSString *)removeTag
{
    return @"removeTag";
}

+ (NSString *)phoneStatus
{
    return @"phoneStatus";
}

+ (NSString *)pcStatus
{
    return @"pcStatus";
}

+ (NSString *)tableName
{
    return @"User";
}


- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    if (!value) {
        if ([key isEqualToString:@"gender"]) {
            self.gender=1;
        }else if ([key isEqualToString:@"userType"]){
            self.userType=1;
        }else if ([key isEqualToString:@"removeTag"]){
            self.removeTag=0;
        }
    }
}

-(NSArray *)insertParamOfUser
{
    return @[[YNIMTool nilFilter:self.userNo],
             [YNIMTool nilFilter:self.userId],
             [YNIMTool nilFilter:self.userName],
             [NSNumber numberWithInt:self.gender],
             [YNIMTool nilFilter:self.dayOfBirth],
             [YNIMTool nilFilter:[XMPPDataSecurity dataEncryptionBy:self.telephone]],
             [YNIMTool nilFilter:[XMPPDataSecurity dataEncryptionBy:self.email]],
             [YNIMTool nilFilter:self.post],
             [YNIMTool nilFilter:self.ownPart],
             [YNIMTool nilFilter:self.headUrl],
             [YNIMTool nilFilter:self.sigature],
             [YNIMTool nilFilter:self.phoneStatus],
             [YNIMTool nilFilter:self.pcStatus],
             [NSNumber numberWithInt:self.userType],
             [NSNumber numberWithInt:self.removeTag]];
}

-(NSArray *)updateParam
{
    return @[[YNIMTool nilFilter:self.userName],
             [YNIMTool nilFilter:self.userId],
             [NSNumber numberWithInt:self.gender],
             [YNIMTool nilFilter:self.dayOfBirth],
             [YNIMTool nilFilter:[XMPPDataSecurity dataEncryptionBy:self.telephone]],
             [YNIMTool nilFilter:[XMPPDataSecurity dataEncryptionBy:self.email]],
             [YNIMTool nilFilter:self.post],
             [YNIMTool nilFilter:self.ownPart],
             [YNIMTool nilFilter:self.headUrl],
             [YNIMTool nilFilter:self.sigature],
             [YNIMTool nilFilter:self.phoneStatus],
             [YNIMTool nilFilter:self.pcStatus],
             [NSNumber numberWithInt:self.userType],
             [NSNumber numberWithInt:self.removeTag],
             [YNIMTool nilFilter:self.userNo]];
}

//创建用户详细信息表
+ (BOOL)createInDatabase:(FMDatabase *)db
{
    if ([db tableExists:[YNUser tableName]])
    {
        ///2021-8-25开始增加的一个字段
        [self insertOneColumnInDatabase:db ColumnName:[YNUser userId] columnDataType:@"varchar(36)"];
        return YES;
    }
    NSString *createUserSql = [NSString stringWithFormat:@"%@%@(%@ varchar(36) NOT NULL PRIMARY KEY UNIQUE, %@ varchar(36), %@ varchar(50), %@ INTEGER, %@ varchar(30),%@ varchar(16),%@ varchar(200),%@ varchar(200),%@ varchar(200),%@ varchar(200),%@ varchar(200), %@ varchar(20),%@ varchar(20), %@ INTEGER, %@ INTEGER)",CREATE_TABLE,
                               [YNUser tableName],
                               [YNUser userNo],
                               [YNUser userId],
                               [YNUser userName],
                               [YNUser gender],
                               [YNUser dayOfBirth],
                               [YNUser telephone],
                               [YNUser email],
                               [YNUser post],
                               [YNUser ownPart],
                               [YNUser headUrl],
                               [YNUser sigature],
                               [YNUser phoneStatus],
                               [YNUser pcStatus],
                               [YNUser userType],
                               [YNUser removeTag]];
    
    BOOL result = [db executeUpdate:createUserSql];
    return result;
}
/**HX** 在表中新增一个列（字段） **/
+ (BOOL)insertOneColumnInDatabase:(FMDatabase*)db ColumnName:(NSString*)name columnDataType:(NSString*)type{
    if (![db columnExists:name inTableWithName:[YNUser tableName]]) {
        //列name在表中不存在，所以加入
        BOOL result= [db executeUpdate:[NSString stringWithFormat:@"%@ %@ add %@ %@",ALTER_TABLE,[YNUser tableName],name,type]];
        return result;
    }
    return YES;
}
//插入用户详细信息
- (BOOL)insertInDatabase:(FMDatabase *)db
{
    NSString *fieldString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@",
                             [YNUser userNo],
                             [YNUser userId],
                             [YNUser userName],
                             [YNUser gender],
                             [YNUser dayOfBirth],
                             [YNUser telephone],
                             [YNUser email],
                             [YNUser post],
                             [YNUser ownPart],
                             [YNUser headUrl],
                             [YNUser sigature],
                             [YNUser phoneStatus],
                             [YNUser pcStatus],
                             [YNUser userType],
                             [YNUser removeTag]];
    
    NSString *insertUserSql = [NSString stringWithFormat:@"%@%@ (%@) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",INSERT_TABLE,[YNUser tableName],fieldString];
    BOOL result = [db executeUpdate:insertUserSql withArgumentsInArray:[self insertParamOfUser]];
    return result;
}

//根据userNo查询用户详细信息
- (NSArray *)queryUserByUserNo:(NSString *)userNo database:(FMDatabase *)db
{
    NSString *queryUserSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?",[YNUser tableName],[YNUser userNo]];
    
    FMResultSet *rs = [db executeQuery:queryUserSql,userNo];
    
    NSMutableArray *userArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNUser *user= [[YNUser alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
             [user setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
        user.telephone=[XMPPDataSecurity dataDecryptionBy:user.telephone];
        user.email=[XMPPDataSecurity dataDecryptionBy:user.email];
        [userArray addObject:user];
    }
    
    [rs close];
    
    return userArray;
}



//查询所有学生信息用户
+ (NSArray *)queryAllStudentUserInDatabase:(FMDatabase *)db
{
    NSString *queryAllUserSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE removeTag = 0 AND userType = 2",[YNUser tableName]];
    
    FMResultSet *rs = [db executeQuery:queryAllUserSql];
    
    NSMutableArray *allUserArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNUser *user= [[YNUser alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [user setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
        
        user.telephone=[XMPPDataSecurity dataDecryptionBy:user.telephone];
        user.email=[XMPPDataSecurity dataDecryptionBy:user.email];
        [allUserArray addObject:user];
    }
    
    [rs close];
    
    return allUserArray;
}

//查询所有老师信息用户
+ (NSArray *)queryAllTeacherStudentUserInDatabase:(FMDatabase *)db
{
    NSString *queryAllUserSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE removeTag = 0 AND userType = 1",[YNUser tableName]];
    
    FMResultSet *rs = [db executeQuery:queryAllUserSql];
    
    NSMutableArray *allUserArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNUser *user= [[YNUser alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [user setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
        
        user.telephone=[XMPPDataSecurity dataDecryptionBy:user.telephone];
        user.email=[XMPPDataSecurity dataDecryptionBy:user.email];
        [allUserArray addObject:user];
    }
    
    [rs close];
    
    return allUserArray;
}


//根据关键字查询User
+ (NSArray *)queryUserByKeywords:(NSString *)keyWords canSearchMe:(BOOL)searchMe database:(FMDatabase *)db onlyGetTeacherData:(BOOL)onlyTeacher
{
    NSString *queryUserByKeywords = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE removeTag = 0 AND (userName like '%%%@%%'escape '/')",[YNUser tableName],keyWords,keyWords];
    if (onlyTeacher) {
        queryUserByKeywords = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE removeTag = 0 AND userType = 1 AND (userName like '%%%@%%'escape '/')",[YNUser tableName],keyWords,keyWords];
    }
    
    FMResultSet *rs = [db executeQuery:queryUserByKeywords];
    
    NSMutableArray *tempUserArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNUser *user= [[YNUser alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [user setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
        
        user.telephone=[XMPPDataSecurity dataDecryptionBy:user.telephone];
        user.email=[XMPPDataSecurity dataDecryptionBy:user.email];
        if (searchMe) {
            [tempUserArray addObject:user];
        }else{
            if (![user.userNo isEqualToString:[YNIMmanager sharedInstance].userImId])
            {
                [tempUserArray addObject:user];
            }
        }
    }
    
    [rs close];
    
    return tempUserArray;
}

//更新用户详细信息
- (BOOL)updateInDatabase:(FMDatabase *)db
{
    NSString *updateUserSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ?, %@ = ?, %@ = ?, %@ = ?,%@ = ?,%@ = ?, %@ = ?,%@ = ?, %@ = ?, %@ = ?, %@ = ?, %@ = ?, %@ = ?, %@ = ? WHERE %@ = ?",[YNUser tableName],
                               [YNUser userName],
                               [YNUser userId],
                               [YNUser gender],
                               [YNUser dayOfBirth],
                               [YNUser telephone],
                               [YNUser email],
                               [YNUser post],
                               [YNUser ownPart],
                               [YNUser headUrl],
                               [YNUser sigature],
                               [YNUser phoneStatus],
                               [YNUser pcStatus],
                               [YNUser userType],
                               [YNUser removeTag],
                               [YNUser userNo]];
    
    BOOL result = [db executeUpdate:updateUserSql withArgumentsInArray:[self updateParam]];
    return result;
}
//判断User是否存在
- (BOOL)isUserExistInDatabase:(FMDatabase *)db
{
    NSArray *userArray = [self queryUserByUserNo:self.userNo database:db];
    
    if (userArray.count > 0)
    {
        return YES;
    }
    
    return NO;
}

//更新用户状态信息
- (BOOL)updateUserStatusInDatabase:(FMDatabase *)db updatePcStatus:(BOOL)pcStatus updatePhoneStatus:(BOOL)phoneStatus
{
    if (pcStatus&&phoneStatus)
    {
        NSString *updateUserStatusSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ?,%@ = ? WHERE %@ = ?",
                                         [YNUser tableName],
                                         [YNUser phoneStatus],
                                         [YNUser pcStatus],
                                         [YNUser userNo]];
        
        BOOL result = [db executeUpdate:updateUserStatusSql,[YNIMTool nilFilter:self.phoneStatus],[YNIMTool nilFilter:self.pcStatus],self.userNo];
        return result;
    }
    else
    {
        if (!pcStatus&&!phoneStatus) {
            return YES;
        }
        NSString *updateField = phoneStatus ? [YNUser phoneStatus] : [YNUser pcStatus];
        NSString *updateParam = phoneStatus ? self.phoneStatus : self.pcStatus;
        NSString *updateUserStatusSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ? WHERE %@ = ?",
                                         [YNUser tableName],
                                         updateField,
                                         [YNUser userNo]];
        
        BOOL result = [db executeUpdate:updateUserStatusSql,[YNIMTool nilFilter:updateParam],self.userNo];
        return result;
    }
}

//更新用户头像url
- (BOOL)updateUserheadUrlInDatabase:(FMDatabase *)db
{
    if ([YNIMTool isEmptyString:self.headUrl]) {
        self.headUrl=nil;
    }
    NSString *updateUserStatusSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ? WHERE %@ = ?",
                                     [YNUser tableName],
                                     [YNUser headUrl],
                                     [YNUser userNo]];
    
    BOOL result = [db executeUpdate:updateUserStatusSql,[YNIMTool nilFilter:self.headUrl],self.userNo];
    return result;
    
}

//删除用户在线状态
+ (BOOL)deleteUserOnlineStatusInDatabase:(FMDatabase *)db
{
    
    NSString *nilStr = [YNIMTool nilFilter:nil];
    
    NSString *updateUserStatusSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ?,%@ = ?",
                                     [YNUser tableName],
                                     [YNUser phoneStatus],
                                     [YNUser pcStatus]];
    
    BOOL result = [db executeUpdate:updateUserStatusSql,nilStr,nilStr];
    
    return result;
}


//根据user查询所属机构
- (NSArray *)queryOrgNoByUserNoInDatabase:(FMDatabase *)db
{
    NSString *unitQuerySql = [NSString stringWithFormat:@"SELECT o.* FROM UserTreeRelation r,OrganizationTree o WHERE r.orgNo = o.orgNo AND r.userNo = ? AND r.removeTag = 0 AND o.removeTag = 0"];
    
    FMResultSet *rs = [db executeQuery:unitQuerySql,self.userNo];
    NSMutableArray *orgArray = [NSMutableArray array];
    while ([rs next])
    {
        YNOrgTree *orgTree = [[YNOrgTree alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [orgTree setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
        
        [orgArray addObject:orgTree];
    }
    
    [rs close];
    
    return orgArray;
}


//删除表中所有数据
+ (BOOL)deleteAllUserDataInDatabase:(FMDatabase *)db
{
    NSString *deleteAllUserSql = [NSString stringWithFormat:@"DELETE FROM %@ ",[YNUser tableName]];
    
    BOOL result = [db executeUpdate:deleteAllUserSql];
    
    return result;
}


//2016-9-9jc添加，逻辑删除表中所有数据
+ (BOOL)logicDeleteAllUserDataInDatabase:(FMDatabase *)db
{
    NSString *updateUserSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = 1",
                               [YNUser tableName],
                               [YNUser removeTag]];
    
    BOOL result = [db executeUpdate:updateUserSql];
    return result;
}
#pragma mark ---------孙浪---------

+ (NSArray *)queryUserByUserNo:(NSString *)userNo database:(FMDatabase *)db
{
    NSString *queryUserSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?",[YNUser tableName],[YNUser userNo]];
    
    FMResultSet *rs = [db executeQuery:queryUserSql,userNo];
    
    NSMutableArray *userArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNUser *user= [[YNUser alloc] init];
        NSDictionary*dicc=[rs resultDictionary];
        if (![YNIMTool isEmptyDictionary:dicc]) {
            [user setValuesForKeysWithDictionary:dicc];
        }
        user.telephone=[XMPPDataSecurity dataDecryptionBy:user.telephone];
        user.email=[XMPPDataSecurity dataDecryptionBy:user.email];
        [userArray addObject:user];
    }
    
    [rs close];
    
    return userArray;
}
///根据用户userId查询用户（用于非im的业务相关）
+ (NSArray *)queryUserByUserId:(NSString *)userId database:(FMDatabase *)db{
    NSString *queryUserSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?",[YNUser tableName],[YNUser userId]];
    
    FMResultSet *rs = [db executeQuery:queryUserSql,userId];
    
    NSMutableArray *userArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNUser *user= [[YNUser alloc] init];
        NSDictionary*dicc=[rs resultDictionary];
        if (![YNIMTool isEmptyDictionary:dicc]) {
            [user setValuesForKeysWithDictionary:dicc];
        }
        user.telephone=[XMPPDataSecurity dataDecryptionBy:user.telephone];
        user.email=[XMPPDataSecurity dataDecryptionBy:user.email];
        [userArray addObject:user];
    }
    
    [rs close];
    
    return userArray;
}

#pragma mark __userState的getter和setter方法来设置在线状态
@synthesize userState = _userState;
-(YNUserStateType)userState{
    if (![YNIMTool isEmptyString:self.phoneStatus] || ![YNIMTool isEmptyString:self.pcStatus])
    {
        if (![YNIMTool isEmptyString:self.phoneStatus])
        {
            _userState = YNUserStateTypeOnlineWithModelPhone;
        }
        else
        {
            _userState = YNUserStateTypeOnlineWithPC;
        }
    }
    else
    {
        _userState = YNUserStateTypeOffline;
    }
    return _userState;
}
-(void)setUserState:(YNUserStateType)userState{
    _userState=userState;
    switch (_userState) {
        case YNUserStateTypeOnlineWithPC:
            {
                self.phoneStatus=nil;
                self.pcStatus=kResource_Online_Phone_PC;
            }
            break;
        case YNUserStateTypeOnlineWithModelPhone:
            {
                self.phoneStatus=kResource_Online_Phone_PC;
            }
            break;
        case YNUserStateTypeOffline:
            {
                self.phoneStatus=nil;
                self.pcStatus=nil;
            }
            break;
            
        default:
            break;
    }
}
@end
